package cn.kgc.springmvc02.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: mosin
 * @version: v1.0  2022/12/13
 * 自定义全局异常处理类
 * @ControllerAdvice  声明当前类为全局异常处理类
 * @RestControllerAdvice = @ControllerAdvice + @ResponseBody
 */
//@ControllerAdvice
//@ResponseBody
@RestControllerAdvice
public class GlobalExceptionHandler {

    //@ExceptionHandler(ArithmeticException.class)
    //public String  arithmeticExceptionHandler(ArithmeticException e){
    //    e.printStackTrace();
    //    return "err";
    //}

    @ExceptionHandler(ArithmeticException.class)
    public Map  arithmeticExceptionHandler(ArithmeticException e){
        e.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "数学运算异常");
        return map;
    }

    @ExceptionHandler(NullPointerException.class)
    //@ResponseBody
    public Map nullPointerExceptionHandler(NullPointerException e){
        e.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "空指针异常");
        return map;
    }


}
